package com.halflife.parameter.icon;

import com.halflife.comeElectricity.basic.datadic.DataDic;
import com.halflife.comeElectricity.basic.datadic.DataDicRepository;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.Page;
import com.halflife.framework.utils.ImageUploadUtil;
import com.halflife.framework.utils.Num62;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class IconAdminController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private IconRepository iconRepository;
    @Resource
    private DataDicRepository dataDicRepository;

    @RequestMapping("/icon/list")
    public String gotoList(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        queryParam.put("valid", true);
        int totalCount = iconRepository.selectCount(queryParam);
        List<Icon> list = iconRepository.selectListByPage(queryParam);
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("list",list);
        model.addAttribute("queryParam",queryParam);
        return "icon/list";
    }
    @RequestMapping("/icon/mock/init")
    public void mock_init(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model) throws Exception{
        File dir = new File("D:\\svg");
        for (File subFile : dir.listFiles()) {
            String catagory = subFile.getName();
            for (File file : subFile.listFiles()) {
                if (file.getName().contains("svg")) {
                    Icon icon = new Icon();
                    icon.setCatagory(catagory);
                    icon.setName(file.getName().replaceAll("\\.svg",""));
                    icon.setValid(true);
                    icon.setPhoto("/svg/icons/"+file.getName());
                    iconRepository.insert(icon);
                }
            }
        }

        response.getWriter().write("asdf");
        response.getWriter().close();
    }
    @RequestMapping(value = "/icon/titleImgeUpload", method = RequestMethod.POST)
    public ResponseEntity<Map<String,Object>> titleImgUpload(HttpServletRequest request, HttpServletResponse response,
                                                             Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            MultipartFile file = multipartRequest.getFile("uploadFile");

            String fileName = null;
            //创建你要保存的文件的路径
            String path = request.getSession().getServletContext().getRealPath("");
            //获取该文件的文件名
            fileName = file.getOriginalFilename();
            //获取拓展名
            String ext = ImageUploadUtil.getExtention(fileName);
            path = path + "svg/icons";
            File targetDir = new File(path);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File targetFile = new File(path, fileName);
            file.transferTo(targetFile);
//            String imageContextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String imageContextPath = "";
            //拼接回传地址
            imageContextPath = "/svg/icons/"+ fileName;

            map.put("SUCESS", true);
            map.put("DATA",imageContextPath);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
    }
    @RequestMapping(value = "/icon/titleImgeUpload1", method = RequestMethod.POST)
    public ResponseEntity<Map<String,Object>> titleImgUpload1(HttpServletRequest request, HttpServletResponse response,
                                                             Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            MultipartFile file = multipartRequest.getFile("uploadFile");

            String fileName = null;
            //创建你要保存的文件的路径
            String path = request.getSession().getServletContext().getRealPath("");
            //获取该文件的文件名
            fileName = file.getOriginalFilename();
            //获取拓展名
            String ext = ImageUploadUtil.getExtention(fileName);
            String svgPath = path + "svg/icons";
            path = path + "svg/icons_origin";
            File targetDir = new File(path);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File targetFile = new File(path, fileName);
            file.transferTo(targetFile);
//            String imageContextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String imageContextPath = "";
            //拼接回传地址
            Thread.sleep(3000l);
            imageContextPath = "/svg/icons_origin/" + fileName;
            IconUtils.convertToSvg(targetFile, svgPath);

            String svgContextPath = "/svg/icons/" + fileName.replaceAll("\\.png","\\.svg");
            map.put("SUCESS", true);
            map.put("DATA",imageContextPath);
            map.put("SVGDATA",svgContextPath);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
    }
    @RequestMapping("/icon/operate")
    public String gotoOperate(Integer id,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        Icon icon = new Icon();
        Map<String, Object> params = new HashMap<>();
        params.put("dataDicTypeId", 14);
        List<DataDic>  catagorys = dataDicRepository.selectAll(params);
        model.addAttribute("catagorys", catagorys);
        if(id!=null){
            icon = iconRepository.selectByPrimaryKey(id);
        }
        model.addAttribute("icon",icon);
        return "icon/operate";
    }

    @PostMapping("/icon/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(Icon icon, HttpServletRequest request,
                              HttpServletResponse response, Model model) {
        try {
            if(icon.getId()!=null){
                iconRepository.updateByPrimaryKey(icon);
            }else {
                icon.init();
                Integer a = iconRepository.insert(icon);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @DeleteMapping("/icon/delete")
    public ResponseEntity setRiderState(Integer id, Integer state) {
        try {
            Icon icon = new Icon();
            icon.setId(id);
            icon.setValid(Boolean.FALSE);
            iconRepository.updateByPrimaryKeySelective(icon);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
}
